<template>
    <el-dialog
      :model-value="visible"
      width="30%"
      title="Excel导入"
      @close="dialogClose"
      >
      <el-form :model="form" ref="formRef" :rules="formRules" label-position="right" label-width="100px" v-loading="loading" element-loading-text="主机配置导入中...">
        <el-form-item label="模板下载：">
<!--            <el-link :href="excelTemplateDown" type="primary">主机模板</el-link>-->
        <el-button type="primary" text  @click="downFile">文件下载</el-button>
        </el-form-item>
         <el-form-item label="IDC机房：" prop="idc">
          <el-select class="m-2" filterable v-model="form.idc" @click="getIdc" placeholder="请选择">
            <el-option v-for="row in idc" :key="row.id" :label="row.name" :value="row.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主机分组：" prop="server_group">
          <el-select class="m-2" filterable  multiple v-model="form.server_group" @click="getServerGroup" placeholder="请选择">
            <el-option v-for="row in serverGroup" :key="row.id" :label="row.name" :value="row.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导入数据：" prop="file">
            <el-upload
              :limit="1"
              v-model:file-list="fileList"
              :auto-upload="false"
            >
              <template #trigger>
                <el-button type="primary">上传文件</el-button>
              </template>
              <template #tip>
                <div class="el-upload__tip text-red">
                 <el-tag type="warning"><el-icon><InfoFilled/></el-icon>
                     导入完成后可通过同步功能采集数据
                 </el-tag>
                </div>
              </template>
            </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogClose">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </span>
      </template>
    </el-dialog>

</template>

<script>
    export default {
        props: {
          visible: Boolean,
        },
        data() {
          return {
            form: [],
            formRules: {
              idc: [
                  {required: true, message: '请选择IDC机房', trigger: 'blur'},
              ],
              server_group: [
                  {required: true, message: '请选择主机分组', trigger: 'blur'},
              ],
            },
            idc: '',
            serverGroup: '',
            // excelTemplateDown: 'http://8.140.193.49:8000/api/cmdb/excel_create_host/',
            // excelTemplateDown: 'https://devops-azhe.oss-cn-beijing.aliyuncs.com/host/host.xlsx',
            fileList: [],
            loading: false
          }
        },
        methods: {
            //处理下载文件，携带token
            downFile() {
             this.$http({
                  method: 'get',
                  url: '/cmdb/excel_create_host/',
                  responseType: 'blob' // 告诉axios我们期望得到一个blob响应
                })
                  .then(res => {
                      // 响应体response.data已经是Blob对象
                      const blob = res.data;
                      // 创建一个a标签用于下载
                      let link = document.createElement('a');
                      link.href = URL.createObjectURL(blob);
                      // 设置下载文件的名称，这里假设this.row.upload是文件名（包括扩展名）
                      link.setAttribute('download', 'host.xlsx');
                       // 模拟点击进行下载
                      link.click();
                      //清理
                      link = null;
                  })
             },
            onRest(){
                this.$refs.formRef.resetFields();
            },
            submit() {
              this.$refs.formRef.validate((valid) => {
                  if (valid) {
                     // console.log(this.fileList)
                      if(!this.fileList.length) {
                        this.$message.warning('请上传文件')
                        return
                       }
                      this.loading = true
                      let fd = new FormData();
                      fd.append("file", this.fileList[0].raw);
                      fd.append('idc', this.form.idc);
                      fd.append('server_group', this.form.server_group);
                      this.$http.post('/cmdb/excel_create_host/', fd)
                        .then(res => {
                          if (res.data.code === 200){
                            this.$message.success('导入成功');
                            this.$parent.getData();  // 调用父组件方法，更新数据
                            this.dialogClose()  // 关闭窗口
                            this.onRest(); //重置表单
                            this.loading = false
                          } else {
                              // this.$message.error(res.data.msg)
                            this.loading = false
                          }
                        })
                          .catch(() => {
                            // this.$message.info('请求服务异常！');
                          })
                      }
                  else {
                    this.$message.warning('格式错误！')
                  }
              })
            },
            // 点击关闭，子组件通知父组件更新属性
            dialogClose() {
              this.$emit('update:visible', false);  // 父组件必须使用v-model
              this.onRest(); //重置表单
            },
            getIdc() {
              console.log(this.$http.instance);
                this.$http.get('/cmdb/idc/?page_size=50')
                    .then(res => {
                        this.idc = res.data.data;
                    })
            },
            getServerGroup() {
                this.$http.get('/cmdb/server_group/?page_size=50')
                    .then(res => {
                        this.serverGroup = res.data.data;
                    });
            },
        }
    }
</script>
